/**
 * 如果 name 字段为数据时，添加与删除 formData，并可回显
 * 
 * */

// 入 excel
const _ = {
	// 获取数据
	getAddData(forms,name){
		return { label: ' ', name, half:true, br:true, colon:false, disabled:true, btn:{ label:'删除', disabled:this.state.edit, ghost:true, danger:true, onClick: ()=> {
			const index = forms.findIndex(v =>v.name === name)			// 找到索引
			forms.splice(index, 1)
			this.setState({ formData: forms })
		}}}
	},
	// 动态添加行
	addRows(forms, name){
		const index = forms.findIndex(v =>v.name === name)			// 找到索引
		const filter = forms.filter(v=>v.name.indexOf(name) >= 0 )	// 找到同类 name
		const newName = name + '|' + (filter.length - 1)			// 动态 name
		
		const { value } = forms[index]
		
		forms.splice(index+1,0, _.getAddData.call(this, forms, newName))
		
		this.setState({ formData: forms }, ()=>{
			this.formRef.setValue({ [newName]: value })
			this.formRef.reset([name])
		})
	},
	// 处理提交数据
	getSubmit(data, name){
		let stack = []
		for(let i in data){
			if( i.indexOf(name + '|') >= 0){
				stack.push( data[i] )
			}
		}
		for(let i in data){
			if( i.indexOf(name + '|') >= 0 ){
				delete data[i]
			}
		}
		return {...data, [name]: stack}
	},
	// 回显数据
	echoName(forms, name, data){
		let stack = {}
		forms.forEach( (v,i) => {
			if( v.name && v.name.indexOf('result_formula|') !== -1 ){
				forms[i] = {}
			}
		} )
		if(window.$fn.hasArray(data)){
			const index = forms.findIndex(v =>v.name === name)			// 找到索引
			data.reverse().forEach((v,i)=>{
				const newName = name + '|' + i			// 动态 name
				forms.splice(index+1,0, _.getAddData.call(this, forms, newName))	// 插入数据行
				stack[newName] = window.$fn.isObject(v) ? v.formula : v
			})
			this.setState({ formData: forms })
		}
		return stack
	}
}

export default _